package com.yupi.yuoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yuoj.annotation.AuthCheck;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.DeleteRequest;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.constant.UserConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.entity.Tags;
import com.yupi.yuoj.service.TagsService;
import com.yupi.yuoj.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * 标签接口
 *
 * @author yupi
 */
@RestController
@RequestMapping("/tags")
@Slf4j
public class TagsController {

    @Resource
    private TagsService tagsService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建标签（仅管理员）
     *
     * @param tags
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addTag(@RequestBody Tags tags, HttpServletRequest request) {
        if (tags == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        tags.setStatus(1); // 默认启用
        tags.setArticleCount(0);
        tags.setFollowCount(0);
        boolean result = tagsService.save(tags);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newTagId = tags.getId();
        return ResultUtils.success(newTagId);
    }

    /**
     * 删除标签（仅管理员）
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteTag(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        Tags oldTag = tagsService.getById(id);
        ThrowUtils.throwIf(oldTag == null, ErrorCode.NOT_FOUND_ERROR);
        boolean b = tagsService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新标签（仅管理员）
     *
     * @param tags
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateTag(@RequestBody Tags tags) {
        if (tags == null || tags.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Tags oldTag = tagsService.getById(tags.getId());
        ThrowUtils.throwIf(oldTag == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = tagsService.updateById(tags);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取标签
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Tags> getTagById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Tags tag = tagsService.getById(id);
        if (tag == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(tag);
    }

    /**
     * 获取所有启用的标签列表
     *
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<Tags>> listTags() {
        List<Tags> tagList = tagsService.lambdaQuery()
                .eq(Tags::getStatus, 1) // 只显示启用的标签
                .orderByDesc(Tags::getArticleCount)
                .orderByAsc(Tags::getId)
                .list();
        return ResultUtils.success(tagList);
    }

    /**
     * 分页获取标签列表（仅管理员）
     *
     * @param current
     * @param size
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Tags>> listTagByPage(@RequestParam long current, @RequestParam long size) {
        Page<Tags> tagPage = tagsService.page(new Page<>(current, size));
        return ResultUtils.success(tagPage);
    }

    /**
     * 根据标识获取标签
     *
     * @param slug
     * @return
     */
    @GetMapping("/slug/{slug}")
    public BaseResponse<Tags> getTagBySlug(@PathVariable String slug) {
        if (slug == null || slug.trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Tags tag = tagsService.lambdaQuery()
                .eq(Tags::getSlug, slug)
                .eq(Tags::getStatus, 1)
                .one();
        if (tag == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(tag);
    }

    /**
     * 获取热门标签
     *
     * @param limit
     * @return
     */
    @GetMapping("/hot")
    public BaseResponse<List<Tags>> getHotTags(@RequestParam(defaultValue = "10") int limit) {
        List<Tags> hotTags = tagsService.lambdaQuery()
                .eq(Tags::getStatus, 1)
                .orderByDesc(Tags::getArticleCount)
                .orderByDesc(Tags::getFollowCount)
                .last("LIMIT " + limit)
                .list();
        return ResultUtils.success(hotTags);
    }

}